package com.leo.tool.jdk.jdk5;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Assert;
import org.junit.Test;

/**
 * @author Leo
 * @date 2019/06/29
 */
public class EnumTest {

    @Test
    public void app() {
        Class<?> type = Gender.class;
        String name = Gender.MALE.name();
        
        if (type.isEnum()) {
            Assert.assertEquals(Gender.MALE, valueOf(type, name));
            Assert.assertEquals(Gender.MALE, reflect(type, name));
        }
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    public Enum<?> valueOf(Class type, String name) {
        return Enum.valueOf(type, name);
    }

    public Enum<?> reflect(Class<?> type, String name) {
        try {
            Method method = type.getMethod("valueOf", String.class);
            return (Enum<?>)method.invoke(null, name);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("方法名错误");
        } catch (SecurityException e) {
            throw new RuntimeException("不能反射");
        } catch (IllegalAccessException e) {
            throw new RuntimeException("没有权限");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("参数错误");
        } catch (InvocationTargetException e) {
            throw new RuntimeException("缺少依赖");
        }
    }

    private enum Gender {
        /** 男 */
        MALE,
        /** 女 */
        FEMALE
    }

}
